/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package Principal;

import de.centigrade.bizlaf.BizLafControl;
import de.centigrade.bizlaf.support.BizLafStyles;
import java.awt.Component;
import java.awt.event.KeyEvent;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.text.NumberFormat;
import java.util.ArrayList;
import java.util.Locale;
import java.util.Vector;
import javax.swing.ImageIcon;
import javax.swing.JTable;
import javax.swing.table.DefaultTableCellRenderer;
import javax.swing.table.DefaultTableModel;
import javax.swing.text.AttributeSet;
import javax.swing.text.BadLocationException;
import javax.swing.text.PlainDocument;

/**
 *
 * @author Tesla
 */
public class cantidad extends javax.swing.JDialog {

    Connection cn;
    PreparedStatement ps;
    ResultSet rs;
    int codigo;
    PrecioCantidad prcd;
    int index;
    int peso;
    String tipo = "";
    Vector cantidades = new Vector();
    Vector precios = new Vector();//almacena los precios por producto
    Vector nombres = new Vector();//almacena los nombres de descuentos
    DefaultTableModel dtm;

    public cantidad(java.awt.Frame parent, boolean modal, int code, PrecioCantidad prec) throws SQLException {
        super(parent, modal);
        initComponents();
        BizLafControl.get().setStyle(jPanel1, BizLafStyles.CONTAINER);
        BizLafControl.get().setStyle(compraron, BizLafStyles.CONTAINER_HEADER);
        BizLafControl.get().setStyle(lblNombre, BizLafStyles.CONTAINER_HEADER);
        BizLafControl.get().setStyle(cantidad, BizLafStyles.BADGE);
        jTable1.getColumnModel().getColumn(2).setCellRenderer(new DecimalFormatRenderer());
        dtm=(DefaultTableModel) jTable1.getModel();
        codigo = code;
        prcd = prec;
        cn = cache_connection.getconnect();
        cargarRecomendados();
        ps = (PreparedStatement) cn.prepareStatement("select nombre, cantidad, peso,tipo from productos left outer join stock on productos.id_producto = stock.id_producto and sucursal = ? where productos.id_producto = ?");
        ps.setInt(2, codigo);
        ps.setInt(1, VentanaPrincipal.sucursal);
        rs = ps.executeQuery();
        rs.next();
        peso = rs.getInt("peso");
        tipo = rs.getString("tipo");
        if (rs.getString("cantidad") != null) {
            cantidad.setText(rs.getString("cantidad"));
        } else {
            cantidad.setText("0");
        }
        jTextField1.setDocument(new LimitadorCaracteres());
        setLabels();
        getRootPane().setDefaultButton(Aceptar);
        if (prcd.getCantidad() == 0) {
            jTextField1.setText("1");
        } else {
            jTextField1.setText(String.valueOf(prcd.getCantidad()));
        }
        jTextField1.requestFocus();
        jTextField1.selectAll();
    }

    private void cargarRecomendados() throws SQLException {
        ps = cn.prepareStatement("select detalleventa.id_producto,productos.nombre,precios.precio from detalleventa \n"
                + "join productos on detalleventa.id_producto = productos.id_producto and activo = 1 \n"
                + "join precios on precios.id_producto = detalleventa.id_producto and precios.sucursal=? and precios.cantidad<2 \n"
                + "where folio in (select folio from detalleventa where id_producto = ?) and detalleventa.id_producto != ? \n"
                + "group by detalleventa.id_producto order by sum(detalleventa.cantidad) desc");
        ps.setInt(1,VentanaPrincipal.sucursal);
        ps.setInt(2, codigo);
        ps.setInt(3, codigo);
        rs=ps.executeQuery();
        ArrayList<Object[]> data = new ArrayList<>();

            while (rs.next()) {
                Object[] rows = new Object[jTable1.getColumnCount()];
                for (int i = 0; i < rows.length; i++) {
                    rows[i] = rs.getObject(i + 1);
                }
                data.add(rows);
            }
            for (int i = 0; i < data.size(); i++) {
                dtm.addRow(data.get(i));
            }
    }
     static class DecimalFormatRenderer extends DefaultTableCellRenderer {

        private static final NumberFormat formatter = NumberFormat.getCurrencyInstance(Locale.getDefault());

        @Override
        public Component getTableCellRendererComponent(
                JTable table, Object value, boolean isSelected, boolean hasFocus, int row, int column) {
            // First format the cell value as required
            if (value == null) {
                value = 0;
            }
            value = formatter.format((Number) value);

            // And pass it on to parent class 
            return super.getTableCellRendererComponent(
                    table, value, isSelected, hasFocus, row, column);
        }
    }

    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jPanel1 = new javax.swing.JPanel();
        cantidad = new javax.swing.JLabel();
        jComboBox1 = new javax.swing.JComboBox();
        jLabel4 = new javax.swing.JLabel();
        labelPrecio = new javax.swing.JLabel();
        jLabel2 = new javax.swing.JLabel();
        jLabel1 = new javax.swing.JLabel();
        jLabel3 = new javax.swing.JLabel();
        compraron = new javax.swing.JLabel();
        jTextField1 = new javax.swing.JTextField();
        jLabel7 = new javax.swing.JLabel();
        lblNombre = new javax.swing.JLabel();
        jScrollPane1 = new javax.swing.JScrollPane();
        jTable1 = new javax.swing.JTable();
        Aceptar = new javax.swing.JButton();
        jButton2 = new javax.swing.JButton();

        setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);
        setTitle("Cantidad A Vender");
        setIconImage(new ImageIcon(getClass().getResource("/Imagenes/logo_rayito.png")).getImage());
        setResizable(false);
        setType(java.awt.Window.Type.POPUP);

        cantidad.setText("-----");

        jComboBox1.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "Item 1", "Item 2", "Item 3", "Item 4" }));
        jComboBox1.addPopupMenuListener(new javax.swing.event.PopupMenuListener() {
            public void popupMenuCanceled(javax.swing.event.PopupMenuEvent evt) {
            }
            public void popupMenuWillBecomeInvisible(javax.swing.event.PopupMenuEvent evt) {
                jComboBox1PopupMenuWillBecomeInvisible(evt);
            }
            public void popupMenuWillBecomeVisible(javax.swing.event.PopupMenuEvent evt) {
            }
        });
        jComboBox1.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                jComboBox1MouseClicked(evt);
            }
        });
        jComboBox1.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jComboBox1ActionPerformed(evt);
            }
        });

        jLabel4.setText("Cantidad:");

        labelPrecio.setFont(new java.awt.Font("Tahoma", 0, 18)); // NOI18N

        jLabel2.setText("Disponibles :");

        jLabel1.setText("Nombre:");

        jLabel3.setText("Precio:");

        compraron.setText("Los que compraron esto tambien compraron");

        jTextField1.setText("1");
        jTextField1.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jTextField1ActionPerformed(evt);
            }
        });
        jTextField1.addKeyListener(new java.awt.event.KeyAdapter() {
            public void keyPressed(java.awt.event.KeyEvent evt) {
                jTextField1KeyPressed(evt);
            }
            public void keyReleased(java.awt.event.KeyEvent evt) {
                jTextField1KeyReleased(evt);
            }
        });

        jLabel7.setFont(new java.awt.Font("Tahoma", 0, 18)); // NOI18N
        jLabel7.setText("$");

        jTable1.setAutoCreateRowSorter(true);
        jTable1.setModel(new javax.swing.table.DefaultTableModel(
            new Object [][] {

            },
            new String [] {
                "ID", "Nombre", "Precio"
            }
        ) {
            Class[] types = new Class [] {
                java.lang.Integer.class, java.lang.String.class, java.lang.Float.class
            };
            boolean[] canEdit = new boolean [] {
                false, false, false
            };

            public Class getColumnClass(int columnIndex) {
                return types [columnIndex];
            }

            public boolean isCellEditable(int rowIndex, int columnIndex) {
                return canEdit [columnIndex];
            }
        });
        jScrollPane1.setViewportView(jTable1);
        if (jTable1.getColumnModel().getColumnCount() > 0) {
            jTable1.getColumnModel().getColumn(0).setMaxWidth(50);
            jTable1.getColumnModel().getColumn(2).setMaxWidth(50);
        }

        Aceptar.setText("Ok");
        Aceptar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                AceptarActionPerformed(evt);
            }
        });

        jButton2.setText("Cancelar");
        jButton2.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton2ActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);
        jPanel1.setLayout(jPanel1Layout);
        jPanel1Layout.setHorizontalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(jPanel1Layout.createSequentialGroup()
                        .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 0, Short.MAX_VALUE)
                        .addContainerGap())
                    .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel1Layout.createSequentialGroup()
                        .addGap(0, 34, Short.MAX_VALUE)
                        .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel1Layout.createSequentialGroup()
                                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                                    .addComponent(compraron)
                                    .addGroup(jPanel1Layout.createSequentialGroup()
                                        .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                                            .addComponent(jLabel2)
                                            .addComponent(jLabel1)
                                            .addComponent(jLabel7)
                                            .addComponent(jLabel3)
                                            .addComponent(jLabel4))
                                        .addGap(18, 18, 18)
                                        .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING, false)
                                            .addComponent(jComboBox1, javax.swing.GroupLayout.Alignment.LEADING, 0, 158, Short.MAX_VALUE)
                                            .addComponent(jTextField1)
                                            .addComponent(lblNombre, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                                            .addComponent(cantidad, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                                            .addComponent(labelPrecio, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))))
                                .addGap(51, 51, 51))
                            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel1Layout.createSequentialGroup()
                                .addComponent(Aceptar, javax.swing.GroupLayout.PREFERRED_SIZE, 88, javax.swing.GroupLayout.PREFERRED_SIZE)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                .addComponent(jButton2, javax.swing.GroupLayout.PREFERRED_SIZE, 88, javax.swing.GroupLayout.PREFERRED_SIZE)
                                .addContainerGap())))))
        );
        jPanel1Layout.setVerticalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jLabel1)
                    .addComponent(lblNombre, javax.swing.GroupLayout.PREFERRED_SIZE, 20, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel2)
                    .addComponent(cantidad))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel3)
                    .addComponent(jComboBox1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel4)
                    .addComponent(jTextField1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                    .addComponent(jLabel7, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                    .addComponent(labelPrecio, javax.swing.GroupLayout.PREFERRED_SIZE, 22, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(compraron)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 143, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jButton2)
                    .addComponent(Aceptar))
                .addGap(35, 35, 35))
        );

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void jTextField1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jTextField1ActionPerformed
        // TODO add your handling code here:
    }//GEN-LAST:event_jTextField1ActionPerformed

    private void jTextField1KeyReleased(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_jTextField1KeyReleased
        if (evt.getKeyCode() == KeyEvent.VK_ENTER) {
            Aceptar.doClick();
        }

        //int seleccion;
        float total;
        float punit = (float) precios.elementAt(0);
        float monto = (jTextField1.getText().equals("")) ? 0 : Float.parseFloat(jTextField1.getText());
        /* for (int i = 0; i < (cantidades.size() - 1); i++) {
         if ((monto >= (int) cantidades.get(i) && (monto < (int) cantidades.get(i + 1)))) {
         punit = (float) (double) precios.elementAt(i);
         index=i;
         }
         }
         if (monto >= (int) cantidades.get(cantidades.size() - 1)) {
         index=cantidades.size() - 1;
         punit = (float) (double) precios.elementAt(index);
         }*///esto de arriba es para los precios automaticos
        punit = (float) precios.elementAt(jComboBox1.getSelectedIndex());
        total = punit * monto;
        labelPrecio.setText(String.valueOf(total) + '0');//el '0' es para el formato del jtextfield


    }//GEN-LAST:event_jTextField1KeyReleased

    private void jComboBox1MouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_jComboBox1MouseClicked
        // TODO add your handling code here:
    }//GEN-LAST:event_jComboBox1MouseClicked

    private void jComboBox1PopupMenuWillBecomeInvisible(javax.swing.event.PopupMenuEvent evt) {//GEN-FIRST:event_jComboBox1PopupMenuWillBecomeInvisible

        float total = 0.0f;
        float punit = 0;
        index = jComboBox1.getSelectedIndex();
        punit = (float) precios.elementAt(index);
        if (!jTextField1.getText().equals("")) {
            total = punit * Float.parseFloat(jTextField1.getText());
        }
        labelPrecio.setText(String.valueOf(total) + '0');//el '0' es para el formato del jtextfield

        // TODO add your handling code here:

    }//GEN-LAST:event_jComboBox1PopupMenuWillBecomeInvisible

    private void jTextField1KeyPressed(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_jTextField1KeyPressed
        if (evt.getExtendedKeyCode() == KeyEvent.VK_ENTER) {
            Aceptar.requestFocusInWindow();
        }
    }//GEN-LAST:event_jTextField1KeyPressed

    private void AceptarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_AceptarActionPerformed

        if (jTextField1.getText().equals("")) {
            prcd.setCantidad(0);
        } else {
            prcd.setCantidad(Float.parseFloat(jTextField1.getText()));
        }

        prcd.setPrecio((float) precios.elementAt(index));
        prcd.setModo(String.valueOf(nombres.elementAt(index)));
        prcd.setPeso(peso);
        prcd.setTipo(tipo);

        this.dispose();

    }//GEN-LAST:event_AceptarActionPerformed

    private void jButton2ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton2ActionPerformed
        prcd.setPrecio((float) 0);
        prcd.setCantidad(0);
        this.dispose();
        // TODO add your handling code here:
    }//GEN-LAST:event_jButton2ActionPerformed

    private void jComboBox1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jComboBox1ActionPerformed
        // TODO add your handling code here:
    }//GEN-LAST:event_jComboBox1ActionPerformed
    private void setLabels() throws SQLException {
        String nombre;
        nombre = rs.getString(1);
        if (nombre.length() >= 25) {
            lblNombre.setText(nombre.substring(0, 25) + "...");
        } else {
            lblNombre.setText(nombre);
        }
        jComboBox1.removeAllItems();
        ps = (PreparedStatement) cn.prepareStatement("select cantidad,precio,nombre from precios where id_producto = ? and sucursal = ? order by cantidad asc");
        ps.setInt(1, codigo);
        ps.setInt(2, VentanaPrincipal.sucursal);
        rs = ps.executeQuery();
        rs.next();
        labelPrecio.setText(rs.getString("precio"));
        cantidades.add(rs.getObject("cantidad"));
        precios.add(rs.getFloat("precio"));
        nombres.add(rs.getObject("nombre"));
        jComboBox1.addItem("(+" + rs.getString("cantidad") + ") " + rs.getString("precio"));
        while (rs.next()) {
            //System.out.println("acaa");
            cantidades.add(rs.getObject("cantidad"));
            precios.add(rs.getFloat("precio"));
            nombres.add(rs.getObject("nombre"));
            jComboBox1.addItem("(+" + rs.getString("cantidad") + ") " + rs.getString("precio"));
        }

    }

    class LimitadorCaracteres extends PlainDocument {

        /**
         * Método al que llama el editor cada vez que se intenta insertar
         * caracteres. Sólo debemos verificar arg1, que es la cadena que se
         * quiere insertar en el JTextField
         */
        @Override
        public void insertString(int arg0, String arg1, AttributeSet arg2) throws BadLocationException {
            for (int i = 0; i < arg1.length(); i++) // si no es digit, volvemos
            {
                if (!(Character.isDigit(arg1.charAt(i)) || arg1.charAt(i) == '.')) {
                    return;
                }
            }

            // Si todos son digit, insertamos el texto en el JTextField
            super.insertString(arg0, arg1, arg2);
        }
    }
    /**
     * @param args the command line arguments
     */
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton Aceptar;
    private javax.swing.JLabel cantidad;
    private javax.swing.JLabel compraron;
    private javax.swing.JButton jButton2;
    private javax.swing.JComboBox jComboBox1;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JLabel jLabel3;
    private javax.swing.JLabel jLabel4;
    private javax.swing.JLabel jLabel7;
    private javax.swing.JPanel jPanel1;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JTable jTable1;
    private javax.swing.JTextField jTextField1;
    private javax.swing.JLabel labelPrecio;
    private javax.swing.JLabel lblNombre;
    // End of variables declaration//GEN-END:variables
}
